package edu.zhuoxun.blogserver.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import edu.zhuoxun.blogserver.entity.Result;
import edu.zhuoxun.blogserver.entity.User;
import edu.zhuoxun.blogserver.map.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Controller
public class RegisterController {
    @Resource
    private UserMapper userMapper;

    @PostMapping("api/register")
    @CrossOrigin
    @ResponseBody
    public Result<User> register(@RequestBody User user) {
        Result<User> result = new Result<>();
        User one = userMapper.selectOne(new QueryWrapper<User>().eq("username", user.getUsername()));
        if (one == null) {
            user.setPassword(toMD5(user.getPassword()));
            userMapper.insert(user);
            result.setCode(200);
            result.setMessage("注册成功");
        } else {
            result.setCode(500);
            result.setMessage("用户名" + user.getUsername() + "已被占用。");
        }
        return result;
    }

    public String toMD5(String src) {
        StringBuilder builder = new StringBuilder();
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] digest = md5.digest(src.getBytes(StandardCharsets.UTF_8));
            for (byte b : digest) {
                builder.append(String.format("%02x", b & 0xff));
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return builder.toString();
    }
}
